<?php

namespace App\Http\Middleware;

use App\Models\Admin;
use Closure;
use Illuminate\Http\Request;

class EnsureTokenIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //var_dump(11111);
        $token = trim(ltrim($request->header('Authorization', ''), 'Bearer'));
        if (!$token) {
            $token = trim(ltrim($request->get('token', '')));
        }
        $info = Admin::getInfoByToken($token);
        $request->userId   = $info['id'] ?? null;
        $request->userInfo = $info ?? [];

        return $next($request);
    }
}
